/**
 * 研发项目创建表单页面
 * 优化版 - 适配小驼峰命名和新数据结构
 */
const cloudHelper = require('../../../config/project_helpers_config').cloudHelper;
const pageHelper = require('../../../config/project_helpers_config').pageHelper;
const formHelper = require('../../../config/path_resolver.js').pageHelper;
const validate = require('../../../config/path_resolver.js').pageHelper;
const projectStore = require('../../../config/path_resolver.js').getRootConfigPath('path_resolver.js').getProjectStorePath('modules/research/project_store').projectStore;
const dayjs = require('dayjs');
const { logEvent } = require('../../../../helpers/log_helper.js');
const { getNetworkStatus, listenNetworkStatus } = require('../../../../helpers/network_helper.js');

Page({
  data: {
    // 表单数据
    formData: {
      projectType: '',
      customerName: '',
      projectTypeName: '',
      description: '',
      startDate: '',
      deadline: '',
      priority: 'normal',
      hasSample: '无',
      sampleCount: '',
      sampleImages: []
    },
    
    // 表单规则
    rules: {
      projectType: [
        { required: true, message: '请选择项目类型' }
      ],
      customerName: [
        { required: true, message: '请填写客户名称' }
      ],
      startDate: [
        { required: true, message: '请选择开始日期' }
      ],
      deadline: [
        { required: true, message: '请选择截止日期' }
      ]
    },
    
    // 选项配置
    options: {
      projectTypes: ['磁编', '霍尔', '风机', '水泵', '吸尘器', '其他'],
      projectTypeNames: {
        '磁编': '电机控制类',
        '霍尔': '电机控制类',
        '风机': '电机控制类',
        '水泵': '电机控制类',
        '吸尘器': '其他类型',
        '其他': '其他类型'
      },
      priorities: [
        { value: 'low', label: '低' },
        { value: 'normal', label: '中' },
        { value: 'high', label: '高' },
        { value: 'urgent', label: '紧急' }
      ],
      hasSampleOptions: ['无', '有'],
    },
    
    // 上传配置
    uploading: false,
    uploadingProgress: 0,
    
    // 页面状态
    showTypeParams: false, // 是否显示特定类型参数
    saving: false
  },
  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function(options) {
    // 网络检测
    const net = await getNetworkStatus();
    if (!net.isConnected) {
      wx.showToast({ title: '当前无网络，请检查连接', icon: 'none' });
    } else if (net.networkType === '2g') {
      wx.showToast({ title: '当前为2G弱网，体验可能受影响', icon: 'none' });
    }
    listenNetworkStatus((res) => {
      if (!res.isConnected) wx.showToast({ title: '网络已断开', icon: 'none' });
      else if (res.networkType === '2g') wx.showToast({ title: '当前为2G弱网', icon: 'none' });
    });
    logEvent('page_load', { page: 'plm_research_create' });
    // 设置默认日期
    const today = dayjs().format('YYYY-MM-DD');
    const nextMonth = dayjs().add(1, 'month').format('YYYY-MM-DD');
    
    this.setData({
      'formData.startDate': today,
      'formData.deadline': nextMonth
    });
  },
  
  /**
   * 表单项变更处理
   */
  onInputChange: function(e) {
    const { field } = e.currentTarget.dataset;
    const { value } = e.detail;
    
    const key = `formData.${field}`;
    this.setData({
      [key]: value
    });
    
    // 项目类型变更时，判断是否需要显示特定参数并设置对应的projectTypeName
    if (field === 'projectType') {
      const showTypeParams = ['磁编', '霍尔', '风机', '水泵'].includes(value);
      // 同时设置projectTypeName
      this.setData({ 
        showTypeParams,
        'formData.projectTypeName': this.data.options.projectTypeNames[value] || '其他类型'
      });
    }
  },
  
  /**
   * 日期选择处理
   */
  onDateChange: function(e) {
    const { field } = e.currentTarget.dataset;
    const { value } = e.detail;
    
    const key = `formData.${field}`;
    this.setData({
      [key]: value
    });
  },
  
  /**
   * 图片上传处理
   */
  onUploadTap: async function() {
    const MAX_UPLOAD = 4;
    if (this.data.formData.sampleImages.length >= MAX_UPLOAD) {
      pageHelper.showModal('最多上传' + MAX_UPLOAD + '张图片');
      return;
    }
    
    const result = await pageHelper.chooseImage(1, false);
    if (!result) return;
    
    this.setData({ uploading: true, uploadingProgress: 0 });
    
    try {
      const cloudPath = 'projects/plm/research/' + pageHelper.genRandomString(32) + '.jpg';
      const uploadResult = await cloudHelper.transTempPic(result[0], cloudPath, this);
      
      if (!uploadResult) {
        pageHelper.showNoneToast('上传图片失败');
        return;
      }
      
      const sampleImages = this.data.formData.sampleImages;
      sampleImages.push(uploadResult.cloudPath);
      
      this.setData({
        'formData.sampleImages': sampleImages
      });
      
    } catch (err) {
      console.error(err);
      pageHelper.showNoneToast('上传失败');
    } finally {
      this.setData({ uploading: false, uploadingProgress: 0 });
    }
  },
  
  /**
   * 删除图片
   */
  onDelTap: function(e) {
    const index = parseInt(e.currentTarget.dataset.index);
    const sampleImages = this.data.formData.sampleImages;
    sampleImages.splice(index, 1);
    
    this.setData({
      'formData.sampleImages': sampleImages
    });
  },
  
  /**
   * 表单提交处理
   */
  onSubmitTap: async function() {
    if (this.data.saving) return;
    
    // 表单校验
    const rules = this.data.rules;
    const formData = this.data.formData;
    
    for (const key in rules) {
      const result = validate.check(formData[key], rules[key]);
      if (!result.success) {
        pageHelper.showModal(result.message);
        return;
      }
    }
    
    // 日期校验
    const startDate = dayjs(formData.startDate);
    const deadline = dayjs(formData.deadline);
    
    if (deadline.isBefore(startDate)) {
      pageHelper.showModal('截止日期不能早于开始日期');
      return;
    }
    
    try {
      this.setData({ saving: true });
      
      // 获取当前用户信息
      const userInfo = projectStore.userInfo || {};
      
      // 准备完整的项目数据，直接使用表单数据，不做映射
      const projectData = {
        // 基础标识信息
        projectType: formData.projectType,
        model: `PRJ-${dayjs().format('YYYYMMDD')}-${Math.floor(Math.random() * 1000).format("YYYY-MM-DD HH:mm:ss").padStart(3, '0')}`,
        
        // 分类与描述信息
        category: '研发',
        projectTypeName: formData.projectTypeName,
        description: formData.description || '',
        
        // 客户信息
        customerName: formData.customerName,
        
        // 申请人信息
        applicantId: userInfo.id || '',
        applicantName: userInfo.name || '',
        
        // 状态信息 - 初始状态为审批中
        level1: 1, // 审批中
        level2: 'director', // 董事长审批
        level3: '',
        level4: '',
        statusDesc: '项目审核 > 董事长',
        priority: formData.priority || 'normal',
        
        // 时间信息
        createTime: Math.floor(dayjs().valueOf() / 1000),
        updateTime: Math.floor(dayjs().valueOf() / 1000),
        stateTime: Math.floor(dayjs().valueOf() / 1000),
        
        // 项目时间点
        startDate: dayjs(formData.startDate).unix(),
        deadline: dayjs(formData.deadline).unix(),
        planStartDate: dayjs(formData.startDate).unix(),
        planEndDate: dayjs(formData.deadline).unix(),
        
        // 样品信息
        hasSample: formData.hasSample,
        sampleCount: formData.sampleCount,
        sampleImages: formData.sampleImages,
      };
      
      // 通过MobX Store提交创建
      await projectStore.createProject(projectData);
      
      pageHelper.showSuccessToast('创建成功', 1500);
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
      
    } catch (err) {
      console.error('创建项目失败', err);
      pageHelper.showModal('创建失败: ' + (err.message || '未知错误'));
    } finally {
      this.setData({ saving: false });
    }
  }
}); 